import router from './router'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useCache } from '@/hooks/web/useCache'
import type { RouteRecordRaw } from 'vue-router'
import { useTitle } from '@/hooks/web/useTitle'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { usePageLoading } from '@/hooks/web/usePageLoading'

const permissionStore = usePermissionStoreWithOut()

const appStore = useAppStoreWithOut()

const { wsCache } = useCache()

const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()

const whiteList = ['/login','/'] // 不重定向白名单
const prefixWhiteList=["/device"]
router.beforeEach(async (to, from, next) => {
  //@ts-ignore
  if(window.__POWERED_BY_WUJIE__&&from.path != "/") {
      //@ts-ignore
      wsCache.set(window.$wujie.props.appName + "_currRouter", to.path);
  }
  start()
  loadStart()
  if (wsCache.get(appStore.getUserInfo)) {
    if (to.path === '/login') {
      // @ts-ignore
      if(window.__POWERED_BY_WUJIE__){
        // @ts-ignore
        window.$wujie.bus.$emit("login")
      }else {
        if(from.path !== '/404') {
          next({ path: '/' })
        } else {
          next()
        }
        
      }

    } else {
      if (permissionStore.getIsAddRouters) {
        next()
        return
      }

      const roleRouters = wsCache.get('roleRouters') || []      

      //const userInfo = wsCache.get(appStore.getUserInfo)    
      await permissionStore.generateRoutes("backend",roleRouters)
      permissionStore.getAddRouters.forEach((route) => {
        router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
      })
       const redirectPath = from.query.redirect || to.path
       const redirect = decodeURIComponent(redirectPath as string)
       const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
      permissionStore.setIsAddRouters(true)
      // @ts-ignore
      if(!window.__POWERED_BY_WUJIE__){
        next(nextData)
      }
    }
  } else {
    let prefixIndex=0;
    for(prefixIndex=0;prefixIndex<prefixWhiteList.length;prefixIndex++){
      if(to.path.startsWith(prefixWhiteList[prefixIndex]))
        break;
    }
    if (whiteList.indexOf(to.path) !== -1||prefixIndex!==prefixWhiteList.length) {
      next()
    } else {
      // @ts-ignore
      if(window.__POWERED_BY_WUJIE__&&!window.$wujie.props.doLogin){
        // @ts-ignore
        window.$wujie.bus.$emit("login",{recirect:to.path})
      }else {
        next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      }
    }
  }
})

router.afterEach((to) => {
  useTitle(to?.meta?.title as string)
  done() // 结束Progress
  loadDone()
})
